<?php

namespace app\company\controller;

use app\admin\model\department\Lists;
use app\admin\model\month\Salary;
use app\admin\model\product\Listo;
use app\admin\model\Signs;
use app\admin\model\user\Sign;
use app\common\controller\CompanyApi;
use app\common\controller\RedisCluster;
use think\Db;

/**
 * 首页接口
 */
class Offices extends CompanyApi
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 假勤列表
     */
    public function index()
    {
        $userId = $this->auth->id;

        $where = [
            'user_id' => $userId,
        ];

        $pageSize = $this->request->post('page_size', 15);
        $status = $this->request->post('status');
        if ($status) {
            $where['status'] = ['in', $status];
        }

        $lists = \app\admin\model\Offices::where($where)
            ->order('id desc')
            ->paginate($pageSize);

        $leaves = config('site.leave');
        foreach ($lists as $val) {
            $val['image'] = make_full_url($val['image']);

            $val->start_time = $val->start_time ? date('Y-m-d H:i', $val->start_time) : '';
            $val->end_time = $val->end_time ? date('Y-m-d H:i', $val->end_time) : '';

            if ($val['type1']) {
                $val['type1'] = $leaves[$val['type1']];
            }
        }

        $this->success('假勤列表！', $lists);
    }

    /**
     * 申请
     */
    public function create()
    {
        $type = $this->request->post('type');
        $type1 = $this->request->post('type1');
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        $sign_time = $this->request->post('sign_time');
        $remark = $this->request->post('remark');
        $to_address = $this->request->post('to_address');
        $image = $this->request->post('image');

        if (!$type || !$remark) {
            $this->error('参数缺失');
        }

        $userId = $this->auth->id;
        if ($start_time) {
            $start_time = strtotime($start_time);
        }
        if ($end_time) {
            $end_time = strtotime($end_time);
        }
        if ($sign_time) {
            $sign_time = strtotime($sign_time);
        }
        $data = [
            'type' => $type,
            'type1' => $type1,
            'user_id' => $userId,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'sign_time' => $sign_time,
            'remark' => $remark,
            'to_address' => $to_address,
            'image' => $image,
        ];

        $ret = \app\admin\model\Offices::create($data);
        if (!$ret) {
            $this->error('申请失败！');
        }

        $this->success('申请成功，等待审批');
    }

    /**
     * 部门请假
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $userId = $this->auth->id;
        $user = \app\admin\model\department\User::find($userId);
        if ($user->is_manager != 1 && $user->is_leader != 1 && $user->is_audit != 1) {
            $this->error('权限不足！');
        }

        $where = [];
        if ($user->is_manager != 1 && $user->is_leader == 1 && $user->is_audit != 1) {
            $department_id = $user->department_id;
            $ids = \app\admin\model\department\User::where('department_id', $department_id)->column('id');
            $where = [
                'user_id' => ['in', $ids],
            ];
        }

        $pageSize = $this->request->post('page_size', 15);
        $status = $this->request->post('status');
        if ($status) {
            $where['status'] = ['in', $status];
        } else {
            if ($user->is_audit == 1) {
                $where['status'] = 5;
            }
        }

        $lists = \app\admin\model\Offices::where($where)
            ->order('id desc')
            ->paginate($pageSize);

        $leaves = config('site.leave');
        foreach ($lists as $val) {
            $val['image'] = make_full_url($val['image']);

            if ($val['audit_time']) {
                $val['audit_time'] = date('Y-m-d H:i', $val['audit_time']);
            }

            if ($val['type1']) {
                $val['type1'] = $leaves[$val['type1']];
            }

            $val->user;
        }

        $this->success('假勤列表！', $lists);
    }

    /**
     * 部门领导审核
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function audit()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        $audit_remark = $this->request->post('audit_remark');
        if (!$id) {
            $this->error('参数缺失！');
        }

        if (!in_array($status, [3, 5])) {
            $this->error('参数非法！');
        }

        $row = \app\admin\model\Offices::find($id);
        if (!$row) {
            $this->error('该记录不存在！');
        }
        if ($row->status != 1) {
            $this->error('该记录不可处理！');
        }
        $userId = $this->auth->id;
        $user = \app\admin\model\department\User::find($userId);
        if ($user->is_leader != 1) {
            $this->error('权限不足！');
        }

        $department_id = $user->department_id;
        $ids = \app\admin\model\department\User::where('department_id', $department_id)->column('id');
        if (!in_array($row->user_id, $ids)) {
            $this->error('权限不足！');
        }

        $row->audit_id = $userId;
        $row->audit_remark = $audit_remark;
        $row->audit_time = time();
        $row->status = $status;
        $ret = $row->save();
        if (!$ret) {
            $this->error('审核失败！');
        }
        $this->success('审核成功！');
    }

    /**
     * 审核员终审
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function finalAudit()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        $audit_remark = $this->request->post('audit_remark');
        if (!$id) {
            $this->error('参数缺失！');
        }

        if (!in_array($status, [7, 10])) {
            $this->error('参数非法！');
        }
        $userId = $this->auth->id;
        $user = \app\admin\model\department\User::find($userId);
        if ($user->is_audit != 1) {
            $this->error('权限不足！');
        }

        $row = \app\admin\model\Offices::find($id);
        if (!$row) {
            $this->error('该记录不存在！');
        }
//        if ($row->status != 5) {
//            $this->error('该记录不可处理！');
//        }

        Db::startTrans();
        try {
            $row->final_audit_id = $userId;
            $row->final_audit_remark = $audit_remark;
            $row->final_audit_time = time();
            $row->status = $status;
            $ret = $row->save();

            if ($status == 10) {
                if ($row->type == 1) {
                    // 补卡
                    $sign_time = $row->start_time;
                    $sdata = [
                        'user_id' => $row->user_id,
                        'image' => $row->image,
                        'createtime' => $sign_time,
                        'remark' => '补卡',
                    ];
                    Sign::create($sdata);

                    $time = strtotime(date('Y-m-d', $sign_time));
                    $sinfo = Signs::where('date', $time)->where('user_id', $row->user_id)->find();

                    if ($sinfo) {
                        $sinfo->num -= 1;
                        if ($sinfo->num <= 0) {
                            Signs::where('id', $sinfo->id)->delete();
                        } else {
                            $sinfo->op = '有补卡';
                        }
                        $sinfo->save();
                    }
                } elseif (in_array($row->type, [3, 4])) {
                    $firstDay = strtotime(date('Y-m-d', $row->start_time));
                    $endDay = strtotime(date('Y-m-d', $row->end_time));
                    $days = ($endDay - $firstDay) / 86400;
                    $data = sign_config($userId);
                    for ($i = 0; $i < $days; $i++) {
                        $day = $firstDay + $i * 86400;
                        $date = date('Y-m-d', $day);
                        foreach ($data as $val) {
                            $begin = strtotime($date . ' ' . $val[0]);
//                            $end = strtotime($date . ' ' . $val[1]);
                            $now = $begin + 10 * 60;
                            if ($now < $row->start_time || $now >= $row->end_time) {
                                continue;
                            }
                            
                            $sdata = [
                                'user_id' => $userId,
                                'createtime' => $now,
                                'image' => '',
                                'is_late' => 0,
                                'remark' => '外出'
                            ];

                            Sign::create($sdata);
                        }
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('审核成功！');
    }
}
